“Make it informative, then make it pretty”
There are two major sets of tools for creating plots in R:
Note that other plotting facilities do exist (notably lattice), but base and ggplot2 are by far the most popular. Base/lattice/ggplot2
For the following examples, we will using the gapminder dataset. Gapminder is a country-year dataset with information on life expectancy, among other things.
gapminder <- read.csv("data/gapminder-FiveYearData.csv", stringsAsFactors = F)
plot(x=)
# Note that when asked to plot a single vector, R will assume the index positions of each vector element are the implied horizontal dimension
plot(x = gapminder$lifeExp)
plot(x=, y=)
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp)
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p")
# Note that "line" does not create a smoothing line, just connected points
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="l")
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="b")
hist(x=gapminder$lifeExp)
hist(x=gapminder$lifeExp, breaks=5)
hist(x=gapminder$lifeExp, breaks=10)
# Plot the density object
plot(density(gapminder$lifeExp))
# Plot the density object, bandwidth of 10
plot(density(gapminder$lifeExp, bw = .5, na.rm=T))
Make a histogram to examine the distribution of the gdpPercap variable.
plot(x=, y=, type="", xlab="", ylab="", main="")
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p", xlab="GDP per cap", ylab="Life Expectancy", main="Life Expectancy ~ GDP") # Add labels for axes and overall plot
Currently it’s hard to see the relationship between the points due to some strong outliers in GDP per capita. We can change the scale of units on the x axis using scaling arguments.
plot(x=, y=, type="", xlim=, ylim=, cex=)
# Create a basic plot
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p")
# Limit gdp (x-axis) to between 1,000 and 20,000
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, xlim = c(1000,20000))
# Limit gdp (x-axis) to between 1,000 and 20,000, increase point size to 2
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, xlim = c(1000,20000), cex=2)
# Limit gdp (x-axis) to between 1,000 and 20,000, decrease point size to 0.5
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, xlim = c(1000,20000), cex=0.5)
plot(x=, y=, type="", col="", pch=, lty=, lwd=)
#colors() # View all elements of the color vector
#colors()[179] # View specific element of the color vector
Another option: R Color Infographic
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p", col=colors()[145]) # or col="gold3"
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p", col="seagreen4") # or col=colors()[578]
# Change point style to crosses
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p", pch=3)
# Change point style to filled squares
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p",pch=15)
# Change point style to filled squares and increase point size to 3
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p",pch=15, cex=3)
# Change point style to "w"
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p", pch="w")
# Change point style to "$" and increase point size to 2
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p",pch="$", cex=2)
# Line plot with solid line
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="l", lty=1)
# Line plot with medium dashed line
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="l", lty=2)
# Line plot with short dashed line
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="l", lty=3)
# Change line width to 2
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="l", lty=3, lwd=2)
# Change line width to 5
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="l", lwd=5)
# Change line width to 10 and use dash-dot
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="l", lty=4, lwd=10)
# plot the line first
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p")
# now add the label
text(x=40000, y=50, labels="Evens Out", cex = .75)
# plot the line
plot(x = gapminder$gdpPercap, y = gapminder$lifeExp, type="p")
# now the guides
abline(v=40000, h=75, lty=2)
Make a scatterplot with population on the x axis and life expectancy on the y axis. Change the color to “peachpuff3” and the point character to “+”
The general call for ggplot2 looks like this:
ggplot(data=, aes(x=, y=), color=, size=,) + geom_xxxx()+ geom_yyyy()
The grammar involves some basic components:
The key to understanding ggplot2 is thinking about a figure in layers: just like you might do in an image editing program like Photoshop, Illustrator, or Inkscape.
Let’s look at an example:
library(ggplot2)
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp)) +
geom_point()
The first thing we do is call the ggplot function. This function lets R know that we’re creating a new plot, and any of the arguments we give the ggplot function are the global options for the plot: they apply to all layers on the plot.
We’ve passed in two arguments to ggplot. First, we tell ggplot what data we want to show on our figure, in this example the gapminder data we read in earlier.
For the second argument we passed in the aes function, which tells ggplot how variables in the data map to aesthetic properties of the figure, in this case the x and y locations. Here we told ggplot we want to plot the lifeExp column of the gapminder data frame on the x-axis, and the gdpPercap column on the y-axis. Notice that we didn’t need to explicitly pass aes these columns (e.g. x = gapminder[, "lifeExp""]), this is because ggplot is smart enough to know to look in the data for that column!
By itself, the call to ggplot isn’t enough to draw a figure:
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp))
We need to tell ggplot how we want to visually represent the data, which we do by adding a new geom layer. In our example, we used geom_point, which tells ggplot we want to visually represent the relationship between x and y as a scatterplot of points:
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp)) + geom_point()
# same as
my_plot <- ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp))
my_plot + geom_point()
Modify the example so that the figure visualise how life expectancy has changed over time:
Hint: the gapminder dataset has a column called “year”“, which should appear on the x-axis.
aesIn the previous examples and challenge we’ve used the aes function to tell the scatterplot geom about the x and y locations of each point. Another aesthetic property we can modify is the point color.
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp, color=continent)) + geom_point()
Normally, specifying options like color="red" or size=10 for a given layer results in its contents being red and quite large. Inside the aes() function, however, these arguments are given entire variables whose values will then be displayed using different realizations of that aesthetic.
Color isn’t the only aesthetic argument we can set to display variation in the data. We can also vary by shape, size, etc.
ggplot(data=, aes(x=, y=, group =, color=, linetype=, shape=, size=))
In the previous challenge, you plotted lifExp over time. Using a scatterplot probably isn’t the best for visualising change over time. Instead, let’s tell ggplot to visualise the data as a line plot:
ggplot(data = gapminder, aes(x=year, y=lifeExp, group=country, color=continent)) + geom_line()
Instead of adding a geom_point layer, we’ve added a geom_line layer. We’ve added the by aesthetic, which tells ggplot to draw a line for each country. group works the same as by.
But what if we want to visualise both lines and points on the plot? We can simply add another layer to the plot:
ggplot(data = gapminder, aes(x=year, y=lifeExp, group=country, color=continent)) + geom_line() + geom_point()
It’s important to note that each layer is drawn on top of the previous layer. In this example, the points have been drawn on top of the lines. Here’s a demonstration:
ggplot(data = gapminder, aes(x=year, y=lifeExp, group=country)) + geom_line(aes(color=continent)) + geom_point()
In this example, the aesthetic mapping of color has been moved from the global plot options in ggplot to the geom_line layer so it no longer applies to the points. Now we can clearly see that the points are drawn on top of the lines.
Switch the order of the point and line layers from the previous example. What happened?
Labels are considered to be their own layers in ggplot.
# add x and y axis labels
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp, color=continent)) + geom_point() + xlab("GDP per capita") + ylab("Life Expectancy") + ggtitle("My fancy graph")
So are scales:
# limit x axis from 1,000 to 20,000
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp, color=continent)) + geom_point() + xlab("GDP per capita") + ylab("Life Expectancy") + ggtitle("My fancy graph") + xlim(1000, 20000)
## Warning: Removed 515 rows containing missing values (geom_point).
ggplot also makes it easy to overlay statistical models over the data. To demonstrate we’ll go back to an earlier example:
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp, color=continent)) + geom_point()
We can change the scale of units on the x axis using the scale functions. These control the mapping between the data values and visual values of an aesthetic.
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp, color=continent)) + geom_point() + scale_x_log10()
The log10 function applied a transformation to the values of the gdpPercap column before rendering them on the plot, so that each multiple of 10 now only corresponds to an increase in 1 on the transformed scale, e.g. a GDP per capita of 1,000 is now 3 on the y axis, a value of 10,000 corresponds to 4 on the x axis and so on. This makes it easier to visualise the spread of data on the x-axis.
We can fit a simple relationship to the data by adding another layer, geom_smooth:
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp, color=continent)) + geom_point() + scale_x_log10() + geom_smooth(method="lm")
Note that we 5 lines, one for each region, because the color option is the global aes function.. But if we move it, we get different restuls:
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp)) + geom_point(aes(color=continent)) + scale_x_log10() + geom_smooth(method="lm")
So there are two ways an aesthetic can be specified. Here we set the color aesthetic by passing it as an argument to geom_point. Previously in the lesson we’ve used the aes function to define a mapping between data variables and their visual representation.
We can make the line thicker by setting the size aesthetic in the geom_smooth layer:
ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp)) + geom_point(aes(color=continent)) + scale_x_log10() + geom_smooth(method="lm", size = 1.5)
Modify the color and size of the points on the point layer in the previous example so that they are fixed (i.e. not reflective of continent).
Hint: do not use the aes function.
We can split this out over multiple panels by adding a layer of facet panels:
ggplot(data = gapminder, aes(x = year, y = lifeExp)) +
geom_point() + facet_wrap( ~ continent)
What if we wanted to facet by countries? We have 142 countries in our dataset. Let’s examine using dplyr to subset our data to countries that start with a or z and plot them.
library(dplyr)
a.z.country <- gapminder %>%
filter(substr(country,1,1) %in% c("A", "Z"))
a.z.country %>%
ggplot(aes(x = year, y = lifeExp, color = continent)) +
geom_line() +
facet_wrap(~ country)
Challenge 4
Suppose I want to visualize a sample of southeast Asian countries and how life expectancy has changed over time. Given the below seAsia vector object, combine dplyr and ggplot2 to subset the data and give each country it’s own facet.
bar plots
# count of lifeExp bins
ggplot(data = gapminder, aes(x = lifeExp)) + geom_bar(stat="bin")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# with color representing regions
ggplot(data = gapminder, aes(x = lifeExp, fill = continent)) + geom_bar(stat="bin")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
density plots**
ggplot(gapminder, aes(lifeExp)) + geom_density(bw = .5, na.rm= T)
box plots**
ggplot(data = gapminder, aes(x = continent, y = lifeExp)) + geom_boxplot()
Create a density plot of GDP per capita, filled by continent excluding Oceania.
Advanced: - Transform the x axis to better visualise the data spread. - Add a facet layer to panel the density plots by year.
gapminder_minusOceania <- gapminder %>% filter(continent != "Oceania")
There are a number of built-in themes:
theme_bw() theme_classic() theme_grey() theme_minimal()
The ggthemes package extends this even further.
Check it out: https://jrnold.github.io/ggthemes/reference/index.html#section-themes
###. Exporting
Two basic image types
Every pixel of a plot contains its own separate coding; not so great if you want to resize the image
jpeg(filename="example.png", width=, height=)
plot(x,y)
dev.off()
Every element of a plot is encoded with a function that gives its coding conditional on several factors; great for resizing
pdf(filename="example.pdf", width=, height=)
plot(x,y)
dev.off()
Exporting with ggplot
# Assume we saved our plot is an object called example.plot
ggsave(filename="example.pdf", plot=example.plot, width= 20, height=20, dpi = 300)
This is just a taste of what you can do with ggplot2. RStudio provides a really useful cheat sheet of the different layers available, and more extensive documentation is available on the ggplot2 website. Finally, if you have no idea how to change something, a quick google search will usually send you to a relevant question and answer on Stack Overflow with reusable code to modify!